<?php
namespace app\admin\controller;

class Role extends Base
{
    private $tn = 'role';

    public function index()
    {
        if (isset($this->get['page']) && isset($this->get['limit'])) {
            $list  = db($this->tn)->field(true)->page($this->get['page'])->limit($this->get['limit'])->select();
            $count = db($this->tn)->count();
            $this->returnAPI('', 0, $list, ['count' => $count, 'limit' => $this->get['limit']]);
        }
        return $this->fetch();
    }

    public function edit($id = 0)
    {
        $model = model($this->tn);
        if ($this->post) {
            if ($id) {
                $model = $model->get($id);
                if (is_null($model)) {
                    $this->returnAPI('信息有误，请稍后重试');
                }
            }
            $result = $model->validate($this->tn)->allowField(true)->save($this->post);
            if ($result !== false) {
                $this->returnAPI('操作成功', 0);
            }
            $this->returnAPI($model->getError());
        }
        $model = $model->get($id);
        if (is_null($model)) {
            $data = $this->table_fields($this->tn);
        } else {
            $data = $model->getData();
        }
        return $this->fetch('', ['data' => $data]);
    }

    public function auth($id)
    {
        $auth  = [];
        $model = model('role')->get($id);
        if (!is_null($model) && $model->auth) {
            $auth = explode(',', $model->auth);
        }
        return $this->fetch('', [
            'id'       => $id,
            'auth'     => $auth,
            'menulist' => $this->menu_list(),
        ]);
    }

    private function menu_list()
    {
        $menu_list = db('menu')->field(['id', 'name', 'route'])->where(['parent_id' => 0, 'disabled' => 0, 'id' => ['>=', 8]])->order(['sort' => 'desc'])->select();
        foreach ($menu_list as $k => $v) {
            if (!$v['route']) {
                $sub_list = db('menu')->field(['id', 'name', 'route'])->where(['parent_id' => $v['id'], 'disabled' => 0, 'id' => ['>=', 8]])->order(['sort' => 'desc'])->select();
                if (empty($sub_list)) {
                    unset($menu_list[$k]);
                } else {
                    $menu_list[$k]['sub'] = $sub_list;
                }
            }
        }
        return $menu_list;
    }
}
